package com.codi.bus.core.event.impl;

import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.dao.OrganProfileDao;
import com.codi.bus.core.dao.TradeOrderDao;
import com.codi.bus.core.dao.UserDao;
import com.codi.bus.core.domain.OrganProfile;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.event.EventBusService;
import com.codi.bus.core.event.EventTypeDef;
import com.codi.bus.core.event.model.BaseEvent;
import com.codi.bus.core.event.model.TradeEvent;
import com.codi.bus.core.resultModel.ApplyListResult;
import com.codi.bus.core.service.model.ApplyModel;
import com.codi.bus.core.service.util.HundsunUtils;
import com.codi.bus.core.service.util.ModelPopulateUtils;
import com.codi.goldlife.external.IntegralServiceApi;
import com.codi.goldlife.external.databean.ResultBean;
import com.codi.trade.service.TradeApplyQueryService;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 模块名
 *
 * @author spy
 * @version 1.0 2017-12-20 14:42
 * @since 1.0
 */
@Slf4j
@Component
public class EventBusServiceImpl implements EventBusService {
    private static final Logger logger = LoggerFactory.getLogger(EventBusServiceImpl.class);

    @Autowired
    private IntegralServiceApi integralServiceApi;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TradeOrderDao tradeOrderDao;

    @Autowired
    private TradeApplyQueryService tradeApplyQueryService;

    @Autowired
    private OrganProfileDao organProfileDao;

//    @Autowired
//    private UserService userService;

    @Override
    public Object post(BaseEvent event) {
        return null;
    }

    @Override
    @Async
    public void postAsync(BaseEvent event) {

        if (event == null || Strings.isNullOrEmpty(event.getEventType())) {
            log.warn("event or event type is null");
            return;
        }

        String msgType = event.getEventType();
        if (msgType.startsWith(EventTypeDef.INTEGRAL_)) {
            processIntegral(event);
            return;
        }

        if (msgType.startsWith(EventTypeDef.TRADE_)) {
            processTradeEvent(event);
            return;
        }
    }

    private void processTradeEvent(BaseEvent event) {
        if (!(event instanceof TradeEvent)) {
            return;
        }
        TradeEvent tradeEvent = (TradeEvent) event;
        User user = userDao.getEntity(tradeEvent.getUserId());
        OrganProfile organProfile = null;
        if (tradeEvent.getProfileId() != null) {
            organProfile = organProfileDao.qryByProfileId(tradeEvent.getProfileId());
        }
        logger.info("事件返回的申请编号：{},用户姓名：{}", tradeEvent.getAllotNo(), user.getUserName());
        List<ApplyModel> fundApplys = new ArrayList<>();
        if (organProfile != null) {
            fundApplys = getOrganApplys(organProfile);
        } else {
            fundApplys = getApplys(user);
        }

        switch (tradeEvent.getEventType()) {
            case EventTypeDef.TRADE_BUY:
                getIntegral(fundApplys, tradeEvent, user);
                break;

            case EventTypeDef.TRADE_BUY_PORTFOLIO:
                getIntegralPortfolio(fundApplys, tradeEvent, user);
                break;

            case EventTypeDef.TRADE_FIX:
                getIntegral(fundApplys, tradeEvent, user);
                break;

        }

        //...
    }

    private List<ApplyModel> getApplys(User user) {
        Map<String, Object> map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
            user.getExternalClientId(), "", "", "", "", "", "", "", "", "", "", "", "");

        // 查询结果
        List<Map<String, Object>> list = new ArrayList<>();
        ApplyListResult result = new ApplyListResult();
        HundsunUtils.ConvertToList(map, list, result);
        List<ApplyModel> fundApplys = ModelPopulateUtils.populateApply2(list, result, null, null, user.getIsOrg());
//        for (ApplyModel applyModel : fundApplys){
//            logger.debug("申请编号：{}，扣款状态：{}，确认状态：{}",applyModel.getAllotNo(),applyModel.getDeductStatus(),applyModel.getTAConfirmFlag());
//        }
        return fundApplys;
    }

    private List<ApplyModel> getOrganApplys(OrganProfile organProfile) {
        Map<String, Object> map = tradeApplyQueryService.query(GlobalConstant.MAX_REQUEST_NUM, 1, 1, "1", "",
            organProfile.getExternalClientId(), "", "", "", "", "", "", "", "", "", "", "", "");

        // 查询结果
        List<Map<String, Object>> list = new ArrayList<>();
        ApplyListResult result = new ApplyListResult();
        HundsunUtils.ConvertToList(map, list, result);
        List<ApplyModel> fundApplys = ModelPopulateUtils.populateApply2(list, result, null, null, true);
//        for (ApplyModel applyModel : fundApplys){
//            logger.debug("申请编号：{}，扣款状态：{}，确认状态：{}",applyModel.getAllotNo(),applyModel.getDeductStatus(),applyModel.getTAConfirmFlag());
//        }
        return fundApplys;
    }

    private void getIntegral(List<ApplyModel> fundApplys, TradeEvent tradeEvent, User user) {
        for (ApplyModel applyModel : fundApplys) {
            if (applyModel.getAllotNo().equals(tradeEvent.getAllotNo())) {
                if (applyModel.getDeductStatus().equals(GlobalConstant.DEDUCT_STATUS_SENT)) {
                    try {
                        tradeEvent.setCount(tradeEvent.getCount() + 1);
                        Thread.sleep(3000);
                        logger.info("次数：{}", tradeEvent.getCount());
                        if (tradeEvent.getCount() == 5) {
                            break;
                        }
                        processTradeEvent(tradeEvent);
                        break;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else if (applyModel.getTAConfirmFlag().equals(GlobalConstant.TACONFIRM_FLAG_UNCONFIRM)
                    && !applyModel.getDeductStatus().equals(GlobalConstant.DEDUCT_STATUS_UNCHECK)
                    && !applyModel.getDeductStatus().equals(GlobalConstant.DEDUCT_STATUS_INVALID)) {
                    logger.info("用户下单成功！！");
                    logger.info("用户名：{}，手机号：{}", user.getUserName(), user.getUserMobile());
                    if (user.getUserInviter() != null) {
                        User inviter = userDao.getEntity(user.getUserInviter());
                        logger.info("邀请人用户名：{}，邀请人手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                    }
                    ResultBean resultBean = integralServiceApi.execIntegral(tradeEvent.getUserId().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_FIRST, user.getUserMobile());
                    if (resultBean.isSuccess()) {
                        logger.info("用户首次购买积分添加成功！！");
                        logger.info("用户名：{}，手机号：{}", user.getUserName(), user.getUserMobile());
                        if (user.getUserInviter() != null) {
                            User inviter = userDao.getEntity(user.getUserInviter());
                            ResultBean resultBean1 = integralServiceApi.execIntegral(user.getUserInviter().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_INVITE_TRANSACTION, inviter.getUserMobile());
                            if (resultBean1.isSuccess()) {
                                logger.info("邀请用户首次购买积分添加成功！！");
                                logger.info("邀请人用户名：{}，手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                            } else {
                                logger.info("邀请用户首次购买积分添加失败");
                                logger.info("邀请人用户名：{}，手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                                logger.info("失败原因：{}", resultBean1.getErrorMessage());
                            }
                        }
                    } else {
                        logger.info("用户首次购买积分添加失败");
                        logger.info("用户名：{}，手机号：{}", user.getUserName(), user.getUserMobile());
                        logger.info("失败原因：{}", resultBean.getErrorMessage());
                    }
                    break;
                }
            }
        }
    }

    private void getIntegralPortfolio(List<ApplyModel> fundApplys, TradeEvent tradeEvent, User user) {
        for (ApplyModel applyModel : fundApplys) {
            if (applyModel.getPortfolioAllotNo().equals(tradeEvent.getAllotNo())) {
                if (applyModel.getDeductStatus().equals(GlobalConstant.DEDUCT_STATUS_SENT)) {
                    try {
                        Thread.sleep(3000);
                        tradeEvent.setCount(tradeEvent.getCount() + 1);
                        logger.debug("次数：{}", tradeEvent.getCount());
                        if (tradeEvent.getCount() == 5) {
                            break;
                        }
                        processTradeEvent(tradeEvent);
                        break;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else if (applyModel.getTAConfirmFlag().equals(GlobalConstant.TACONFIRM_FLAG_UNCONFIRM)
                    && !applyModel.getDeductStatus().equals(GlobalConstant.DEDUCT_STATUS_UNCHECK)
                    && !applyModel.getDeductStatus().equals(GlobalConstant.DEDUCT_STATUS_INVALID)) {
                    logger.info("用户下单成功！！");
                    logger.info("用户名：{}，手机号：{}", user.getUserName(), user.getUserMobile());
                    if (user.getUserInviter() != null) {
                        User inviter = userDao.getEntity(user.getUserInviter());
                        logger.info("邀请人用户名：{}，邀请人手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                    }
                    ResultBean resultBean = integralServiceApi.execIntegral(tradeEvent.getUserId().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_FIRST, user.getUserMobile());
                    if (resultBean.isSuccess()) {
                        logger.info("用户首次购买积分添加成功！！");
                        logger.info("用户名：{}，手机号：{}", user.getUserName(), user.getUserMobile());
                        if (user.getUserInviter() != null) {
                            User inviter = userDao.getEntity(user.getUserInviter());
                            ResultBean resultBean1 = integralServiceApi.execIntegral(user.getUserInviter().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_INVITE_TRANSACTION, inviter.getUserMobile());
                            if (resultBean1.isSuccess()) {
                                logger.info("邀请用户首次购买积分添加成功！！");
                                logger.info("邀请人用户名：{}，手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                            } else {
                                logger.info("邀请用户首次购买积分添加失败");
                                logger.info("失败原因：{}", resultBean1.getErrorMessage());
                                logger.info("邀请人用户名：{}，手机号：{}", inviter.getUserName(), inviter.getUserMobile());
                            }
                        }
                    } else {
                        logger.info("用户首次购买积分添加失败");
                        logger.info("用户名：{}，手机号：{}", user.getUserName(), user.getUserMobile());
                        logger.info("失败原因：{}", resultBean.getErrorMessage());
                    }
                }
            }
        }
    }

    private void processIntegral(BaseEvent event) {
        log.info("process integral event");

        //成功确认完成 货币基金 普通基金 组合基金 会添加积分
        //首次完成交易 会为邀请人添加积分
        switch (event.getEventType()) {
            //规则修改  不管买什么 只有买第一笔才会添加积分
//            case INTEGRAL_CURRENCY_BUY_CONFIRM_SUC:
//                Map currencyMessageMap = (Map) event.getMessage();
//                integralServiceApi.execIntegral((String) currencyMessageMap.get("userId"), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_CURRENCY);
//                break;
//
//            case INTEGRAL_FUND_BUY_CONFIRM_SUC:
//                Map fundMessageMap = (Map) event.getMessage();
//                integralServiceApi.execIntegral((String) fundMessageMap.get("userId"), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_FUND);
//                break;
//
//            case INTEGRAL_PORTFOLIO_BUY_CONFIRM_SUC:
//                Map portfolioMessageMap = (Map) event.getMessage();
//                integralServiceApi.execIntegral((String) portfolioMessageMap.get("userId"), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_PORTFOLIO);
//                break;
//
//            case INTEGRAL_CURRENCY_BUY_CONFIRM_SUC_FIRST:
//                Map currencyMessageMap1 = (Map) event.getMessage();
//                integralServiceApi.execIntegral((String) currencyMessageMap1.get("userId"), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_CURRENCY);
//                integralServiceApi.execIntegral((String) currencyMessageMap1.get("inviterId"), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_INVITE_TRANSACTION);
//                break;
//
//            case INTEGRAL_FUND_BUY_CONFIRM_SUC_FIRST:
//                Map fundMessageMap1 = (Map) event.getMessage();
//                integralServiceApi.execIntegral((String) fundMessageMap1.get("userId"), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_FUND);
//                integralServiceApi.execIntegral((String) fundMessageMap1.get("inviterId"), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_INVITE_TRANSACTION);
//                break;

//            case TRADE_COMFIRM_SUC:
//                EventMsg message = (EventMsg) event.getMessage();
//                if (message.getTradeType().contains("BUY")){
//                    Integer count = tradeOrderDao.getCountBeforeConfirmDate(message.getUserId(), message.getConfirmDate());
//                    if (count == 0){
//                        integralServiceApi.execIntegral(message.getUserId().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_FIRST);
//                        User user = userDao.getEntity(message.getUserId());
//                        if (user.getUserInviter() != null){
//                            integralServiceApi.execIntegral(user.getUserInviter().toString(), GlobalConstant.INTEGRAL_CHANNEL_ID, GlobalConstant.INTEGRAL_BUSINESSID_INVITE_TRANSACTION);
//                        }
//                    }
//                    break;
//                }

        }
    }
}
